﻿<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1200"
        destroy-on-close
        @closed="$emit('closed')"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="价格表编号" prop="deliveryProtocolCode">
                        <el-input v-model="entityObj.deliveryProtocolCode" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="价格表名称" prop="deliveryProtocolName">
                        <el-input v-model="entityObj.deliveryProtocolName" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <!-- <el-col :span="12">
                    <el-form-item label-width="120px" label="价格表有效期" prop="protocolDate">
                        <el-date-picker
                            style="width: 100%"
                            v-model="entityObj.protocolDate"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            @change="changeProtocolDate"
                        />
                    </el-form-item>
                </el-col>-->
                <el-col :span="12">
                    <el-form-item label-width="120px" label="供货单位" prop="purchaseUnityName">
                        <el-input v-model="entityObj.purchaseUnityName" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="创建人" prop="crName">
                        <el-input v-model="entityObj.crName" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="创建时间" prop="crDate">
                        <el-date-picker
                            v-model="entityObj.crDate"
                            :default-time="defaultTime"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            placeholder="请输入创建时间"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="要货客户类型" prop="storeOrgType">
                        <el-select
                            placeholder="---请选择要货客户类型---"
                            v-model="entityObj.storeOrgType"
                            style="width: 100%"
                            @change="storeOrgTypeChange"
                        >
                            <el-option label="---请选择---" value />
                            <el-option
                                v-for="item in optionsStoreOrgType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                
            </el-row>
            <el-row>
                <el-col :span="12" v-if="entityObj.storeOrgType==2">
                    <el-form-item label="客户名称" label-width="120px" >
                        <sc-store-select
                            ref="storeSelect"
                            :props="storeProps"
                            :selectKeyValue="'storeId'"
                            v-model="entityObj.store"
                            :multiple="false"
                            style="width: 100%"
                            @fatherMethod="storeSelectProcess"
                        ></sc-store-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="entityObj.storeOrgType==3">
                    <el-form-item label="客户名称" label-width="120px" >
                        <sc-supplier-select
                            ref="supplierSelect"
                            :props="storeProps"
                            :selectKeyValue="'storeId'"
                            v-model="entityObj.store"
                            :multiple="false"
                            style="width: 100%"
                            @fatherMethod="supplierSelectProcess"
                        ></sc-supplier-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label-width="120px" label="状态">
                        <el-switch
                            v-model="entityObj.status"
                            :active-value="1"
                            :inactive-value="0"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row></el-row>
            <!-- <el-row v-if="orgType==1">
                <el-col :span="12">
                    <el-form-item label-width="120px" label="要货单位" prop="stores">
                        <el-button size="small" @click="addStore()">选择门店</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="orgType==1"> 
                <el-col :span="24">
                    <el-form-item label-width="120px">
                        <el-table
                            :data="entityObj.deliveryProtocolStores"
                            border
                            style="width: 100%"
                        >
                            <el-table-column label="门店编号" width="180">
                                <template #default="scope">{{scope.row.storeCode}}</template>
                            </el-table-column>
                            <el-table-column label="门店名称" width="180">
                                <template #default="scope">{{scope.row.storeName}}</template>
                            </el-table-column>
                            <el-table-column label="品牌" width="180">
                                <template #default="scope">{{scope.row.brandName}}</template>
                            </el-table-column>
                            <el-table-column label="备注" width="230" prop="remarks">
                                <template #default="scope">{{scope.row.remarks}}</template>
                            </el-table-column>
                            <el-table-column label="操作">
                                <template #default="scope">
                                    <el-button
                                        size="small"
                                        @click="deleteStoreRow(scope.$index, scope.row)"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>-->
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="备注">
                        <el-input v-model="entityObj.remarks" type="textarea" :rows="2" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="相关附件" prop="protocolFile">
                        <sc-upload-file
                            v-model="entityObj.protocolFile"
                            :objName="'Supply/deliveryProtocol'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="1"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="调价函上传">
                        <sc-upload-file
                            v-model="entityObj.protocolPriceFileStr"
                            :objName="'Supply/deliveryProtocol'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="10"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="价格表" prop="materialItems">
                        <el-button size="small" @click="addMaterial()">添加物料</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px">
                        <el-form inline label-width="49px" style="margin-top: 5px">
                            <el-form-item label="物料编号" label-width="80px">
                                <el-input
                                    placeholder="---请输入编号---"
                                    v-model="queryList.materialCode"
                                    style="width: 160px"
                                />
                            </el-form-item>
                            <el-form-item label="物料名称" label-width="80px">
                                <el-input
                                    placeholder="---请输入名称---"
                                    v-model="queryList.materialName"
                                    style="width: 160px"
                                />
                            </el-form-item>
                            <el-form-item label="物料分类" label-width="80px">
                                <el-tree-select
                                    collapse-tags
                                    collapse-tags-tooltip
                                    placeholder="---请选择物料分类---"
                                    v-model="queryList.materialTypeIds"
                                    :props="{ label: 'label', value:'value',children: 'children' }"
                                    :data="materialTypeTree"
                                    multiple
                                    :render-after-expand="false"
                                    show-checkbox
                                    style="width: 160px"
                                />
                            </el-form-item>
                            <el-button
                                :icon="Search"
                                type="primary"
                                @click="handleSearch"
                            >查询</el-button>
                            <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                            <el-form inline label-width="49px" style="margin-top: 5px"></el-form>
                        </el-form>
                        <el-table :data="itemsData" border style="width: 100%;height: 500px;">
                            <el-table-column label="操作" min-width="180" v-if="orgType==1">
                                <template #default="scope">
                                    <el-button
                                        size="small"
                                        @click="opSetRowPrice(scope.row,scope.$index)"
                                    >进供价{{scope.row.protocolItemRelations&&scope.row.protocolItemRelations.length>0?"/"+scope.row.protocolItemRelations.length:""}}</el-button>
                                    <el-button
                                        size="small"
                                        @click="deleteRow(scope.$index, scope.row)"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" min-width="120" prop="materialItemId">
                                <template #default="scope">
                                    <el-select
                                        placeholder="---单位---"
                                        v-model="scope.row.materialItemId"
                                        style="width: 90px"
                                        :disabled="scope.row.deliveryProtocolItemId>0"
                                    >
                                        <el-option
                                            v-for="item in scope.row.materialItems"
                                            :key="item.materialItemId"
                                            :label="item.unitName"
                                            :value="item.materialItemId"
                                        />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="是否一次性物料" min-width="140" v-if="orgType==1">
                                <template #default="scope">
                                    <el-switch
                                        v-model="scope.row.isDisposable"
                                        :active-value="true"
                                        :inactive-value="false"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="含税单价" min-width="140" prop="price">
                                <template #default="scope">
                                    <span v-if="orgType==1">{{currentPrice(scope.row)}}</span>
                                    <span v-else>{{scope.row.price}}</span>
                                    <!-- <el-input-number
                                        v-model="scope.row.price"
                                        style="width: 100%"
                                        :precision="2"
                                        :step="0.00"
                                        controls-position="right"
                                        disabled
                                    ></el-input-number> -->
                                </template>
                            </el-table-column>
                            <el-table-column label="物料编码" min-width="110">
                                <template #default="scope">{{scope.row.materialCode}}</template>
                            </el-table-column>
                            <el-table-column label="物料简码" min-width="130">
                                <template #default="scope">{{scope.row.materialSimpCode}}</template>
                            </el-table-column>
                            <el-table-column label="物料名称" min-width="200">
                                <template #default="scope">{{scope.row.materialName}}</template>
                            </el-table-column>
                            <el-table-column label="规格" min-width="160">
                                <template #default="scope">{{scope.row.materialSpecs}}</template>
                            </el-table-column>
                            <el-table-column label="物料类别" min-width="130">
                                <template #default="scope">{{scope.row.materialTypeName}}</template>
                            </el-table-column>
                            <el-table-column label="开票类型" min-width="120" prop="ticketType">
                                <template #default="scope">
                                    <el-select
                                        placeholder="---开票类型---"
                                        v-model="scope.row.ticketType"
                                        style="width: 90px"
                                    >
                                        <el-option
                                            v-for="item in optionsTicketType"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                        />
                                    </el-select>
                                </template>
                            </el-table-column>

                            <!-- <el-table-column label="当前含税单价" min-width="140" prop="price">
                                <template #default="scope">{{currentPrice(scope.row)}}</template>
                            </el-table-column>
                            <el-table-column label="不含税单价" min-width="140" prop="notTaxPrice">
                                <template #default="scope">
                                    <span
                                        v-if="scope.row.ticketType==0"
                                    >{{currentPrice(scope.row).toFixed(2)}}</span>
                                    <span
                                        v-else-if="scope.row.ticketType==1"
                                    >{{(currentPrice(scope.row)/(1+scope.row.generalRate/100)).toFixed(2)}}</span>
                                    <span
                                        v-else
                                    >{{(currentPrice(scope.row)/(1+scope.row.incrementRate/100)).toFixed(2)}}</span>
                                </template>
                            </el-table-column>-->
                            <el-table-column label="普票税率" min-width="160" prop="generalRate">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.generalRate"
                                        style="width: 100%"
                                        :precision="2"
                                        :step="0.01"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="增票税率" min-width="160" prop="incrementRate">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.incrementRate"
                                        style="width: 100%"
                                        :precision="2"
                                        :step="0.01"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="起送量" min-width="120" prop="minOrderQty">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.minOrderQty"
                                        style="width: 100%"
                                        :step="1"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column> -->
                            <el-table-column label="备注" min-width="160" prop="remarks">
                                <template #default="scope">
                                    <el-input v-model="scope.row.remarks" style="width: 100%" />
                                </template>
                            </el-table-column>
                            <el-table-column label="富文本备注" min-width="160" prop="notes">
                                <template #default="scope">
                                    <div v-html="scope.row.notes" style="width: 100%"></div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item
                        label-width="120px"
                        label="记录数"
                    >{{entityObj.deliveryProtocolItems?.length??0}}</el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit()"
            >保 存</el-button>
        </template>

        <template>
            <full-screen-dialog
                v-model="materialState"
                title="选择商品"
                :width="1000"
                :center="true"
                append-to-body
            >
                <el-row>
                    <sc-material-choice
                        ref="scMaterialChoice"
                        :queryList="materialQueryList"
                        @selection-changed="handleSelectionChanged"
                    ></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </full-screen-dialog>
        </template>

        <template>
            <full-screen-dialog
                v-model="storeState"
                title="选择门店"
                :width="1000"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row>
                    <sc-store-choice
                        ref="scStoreChoice"
                        :queryList="{brandCode:entityObj.brandCode}"
                    ></sc-store-choice>
                </el-row>
                <template #footer>
                    <el-button @click="storeState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setStoreChoice">确定</el-button>
                </template>
            </full-screen-dialog>
        </template>

        <price-dialog
            v-if="dialogPrice"
            ref="priceDialog"
            @setPrice="setPrice"
            @closed="dialogPrice = false"
        ></price-dialog>
    </full-screen-dialog>
</template>

<script>
import tool from "@/utils/tool";
import priceDialog from "./price";
export default {
    components: {
        priceDialog,
    },
    emits: ["success", "closed"],
    data() {
        return {
            dialogPrice: false,
            orgType: 0,
            mode: "Add",
            titleMap: {
                Add: "新增价格表",
                Edit: "编辑价格表",
                Show: "价格表详情",
            },
            entityObj: {
                deliveryProtocolId: 0,
                deliveryProtocolCode: "",
                deliveryProtocolName: "",
                status: 1,
                crName: "",
                crDate: "",
                supplier: {},
                protocolDate: [],
                deliveryUnityName: "",
                remarks: "",
                protocolFile: "",
                deliveryProtocolItems: [],
                deliveryProtocolStores: [],
            },
            materialQueryList: [],
            materialState: false,
            storeState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            optionsStoreOrgType:[{value:2,label:"门店"},{value:3,label:"供应商"}],
            //验证规则
            rules: {
                deliveryProtocolName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                purchaseUnityName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                supplier: [
                    { required: true, type: "object", message: "请填写" },
                ],
                protocolDate: [
                    { required: true, type: "array", message: "请填写" },
                ],
                crName: [{ required: true, type: "string", message: "请填写" }],
                crDate: [{ required: true, type: "string", message: "请填写" }],
                materialSpecs: [
                    { required: true, type: "string", message: "请填写" },
                ],
                deliveryProtocolItems: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写",
                        trigger: "change",
                    },
                ],
            },
            props: {
                label: "supplierName",
                value: "supplierId",
            },
            storeProps: {
                label: "storeName",
                value: "storeId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsBrand: [],
            optionsUnit: [],
            itemsData: [],
            optionsTicketType: [],
        };
    },
    computed: {
        // itemsData() {
        //     let filtered = this.entityObj.deliveryProtocolItems;
        //     if (this.queryList.materialTypeIds&&this.queryList.materialTypeIds.length>0) {
        //         filtered = filtered.filter(item => {
        //             return this.queryList.materialTypeIds.includes(item.materialTypeId);
        //         });
        //     }
        //     if (this.queryList.materialCode) {
        //         filtered = filtered.filter(item => {
        //             return item.materialCode.includes(this.queryList.materialCode);
        //         });
        //     }
        //     if (this.queryList.materialName) {
        //         filtered = filtered.filter(item => {
        //             return item.materialName.includes(this.queryList.materialName);
        //         });
        //     }
        //     return filtered;
        // },
    },
    methods: {
        handleSelectionChanged(selectionRows) {
            this.setMaterialChoice();
        },
        //获取当前生效价格
        currentPrice(row) {
            const currentDate = new Date();
            const deliveryProtocolItemPrices=row.protocolItemRelations.filter(p=>p.isValid==true).flatMap(p => p.deliveryProtocolItemPrices)
            let price= deliveryProtocolItemPrices.find(p => new Date(p.validityDates[1]) >= currentDate&&new Date(p.validityDates[0]) <= currentDate)?.price;
            if(!price){
                const deliveryProtocolItemPrices=row.protocolItemRelations.flatMap(p => p.deliveryProtocolItemPrices)
                price= deliveryProtocolItemPrices.find(p => new Date(p.validityDates[1]) >= currentDate&&new Date(p.validityDates[0]) <= currentDate)?.price;
            }
            return price;
        },
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    if (
                        !this.entityObj.deliveryProtocolItems ||
                        this.entityObj.deliveryProtocolItems.length == 0
                    ) {
                        this.$message.error("协议内容不能为空");
                        return;
                    }

                    if (this.entityObj.deliveryProtocolItems.some(p=>!p.materialItemId || p.materialItemId < 0)) {
                        this.$message.error("单位不能为空");
                        return false;
                    }

                    if (this.entityObj.deliveryProtocolItems.some(p=>!p.protocolItemRelations ||p.protocolItemRelations.length == 0)) {
                        this.$message.error("采购单价不能为空");
                        return false;
                    }

                    this.entityObj.startDate = this.entityObj.protocolDate[0];
                    this.entityObj.endDate = this.entityObj.protocolDate[1];
                    this.entityObj.supplierId =
                        this.entityObj.supplier.supplierId;
                    this.entityObj.supplierName =
                        this.entityObj.supplier.supplierName;
                    console.log(this.entityObj.protocolDate);
                    this.entityObj.deliveryProtocolItems.map((p) => {
                        if (
                            !p.deliveryProtocolItemPrices ||
                            p.deliveryProtocolItemPrices.length == 0
                        ) {
                            p.deliveryProtocolItemPrices = [
                                {
                                    price: p.price,
                                    validityDates: this.entityObj.protocolDate,
                                },
                            ];
                        }
                    });
                    this.isSaveing = true;
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                this.mode == "Add"
                                    ? "delivery-protocol/create"
                                    : "delivery-protocol/update",
                                { ...this.entityObj }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(data) {
            console.log("delivery-protocol-setData", data);
            const materialIds = data.deliveryProtocolItems.map(
                (p) => p.materialId
            );
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "material/pages",
                { pageIndex: 1, pageSize: 9999, materialIds: materialIds }
            );
            if (returnValue.status == 200) {
                const materials = returnValue.response.data;
                this.entityObj = {
                    ...data,
                    supplier: {
                        supplierId: data.supplierId,
                        supplierName: data.supplierName,
                    },
                    protocolDate: [data.startDate, data.endDate],
                    protocolFile: data.protocolFile ?? "",
                    purchaseUnityId: data.purchaseUnityId,
                    deliveryProtocolItems: [],
                    deliveryProtocolStores: data.deliveryProtocolStores,
                };
                data.deliveryProtocolItems.map((p) => {
                    const material = materials.find(
                        (t) => t.materialId == p.materialId
                    );
                     
                    console.log(p.materialId)
                    this.entityObj.deliveryProtocolItems.push({
                        deliveryProtocolItemId: p.deliveryProtocolItemId,
                        materialId: material.materialId,
                        materialCode: material.materialCode,
                        materialName: material.materialName,
                        materialSpecs: material.materialSpecs,
                        materialSimpCode: material.materialSimpCode, 
                        materialTypeId: material.materialTypeId,
                        materialTypeName: material.materialTypeName,
                        unitCode: material.unitCode,
                        unitName: material.unitName,
                        price: p.price,
                        ticketType: p.ticketType,
                        generalRate: p.generalRate,
                        incrementRate: p.incrementRate,
                        recoverPrice: 0,
                        remarks: p.remarks,
                        notes: p.notes,
                        materialItemId: p.materialItemId,
                        materialItems: material.materialItems,
                        isDisposable: p.isDisposable,
                        deliveryProtocolItemPrices:
                            p.deliveryProtocolItemPrices,
                        protocolItemRelations: p.protocolItemRelations,
                        minOrderQty:p.minOrderQty
                    });
                });
                this.queryList = {};
                this.handleSearch();
            }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    { status: 1 }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/dic-options",
                    { ParentBaseDictionaryCodes: ["001"] }
                );
                if (returnValue.status == 200) {
                    this.optionsBrand = returnValue.response.find(
                        (p) => p.code == "001"
                    ).optionsDetails;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/options",
                    { Codes: ["TicketType"] }
                );
                if (returnValue.status == 200) {
                    this.optionsTicketType = returnValue.response.find(
                        (p) => p.code == "TicketType"
                    ).optionsDetails;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        
        addStore() {
            this.storeState = true;
        },
        deleteStoreRow(index) {
            this.entityObj.deliveryProtocolStores.splice(index, 1);
        },
        setStoreChoice() {
            let stores = this.$refs.scStoreChoice.selectionRows;
            stores.map((p) => {
                const store = this.entityObj.deliveryProtocolStores.find(
                    (t) => t.storeId == p.storeId
                );
                if (!store) {
                    this.entityObj.deliveryProtocolStores.push({
                        storeId: p.storeId,
                        storeCode: p.storeCode,
                        storeName: p.storeName,
                        brandName: p.brandName,
                        remarks: p.remarks,
                    });
                }
            });
            this.storeState = false;
        },
        addMaterial() {
            // if (!this.entityObj.brandCode) {
            //     this.$message.error("请选品牌");
            //     return;
            // }
            this.materialState = true;
            this.$nextTick(() => {
                this.materialQueryList = {
                    //brandCode: this.entityObj.brandCode,
                };
            });
        },
        deleteRow(index) {
            const item = this.itemsData[index];
            this.entityObj.deliveryProtocolItems =
                this.entityObj.deliveryProtocolItems.filter((p) => item !== p);
            this.handleSearch();
        },
        resetSearch() {
            this.queryList = {};
        },
        handleSearch() {
            this.itemsData = this.entityObj.deliveryProtocolItems;
            if (
                this.queryList.materialTypeIds &&
                this.queryList.materialTypeIds.length > 0
            ) {
                console.log("分类搜索");
                this.itemsData = this.itemsData.filter((item) => {
                    return this.queryList.materialTypeIds.includes(
                        item.materialTypeId
                    );
                });
            }

            if (this.queryList.materialCode) {
                console.log("编码搜索");
                this.itemsData = this.itemsData.filter((item) => {
                    return (
                        item.materialCode.includes(
                            this.queryList.materialCode
                        ) ||
                        item.materialSimpCode.includes(
                            this.queryList.materialCode
                        )
                    );
                });
            }

            if (this.queryList.materialName) {
                console.log("名称搜索");
                this.itemsData = this.itemsData.filter((item) => {
                    console.log("item", item.materialName);
                    return item.materialName.includes(
                        this.queryList.materialName
                    );
                });
                console.log("搜索结果", this.itemsData);
            }
            //console.log(this.entityObj.deliveryProtocolItems);
        },
        setMaterialChoice() {
            let materials = this.$refs.scMaterialChoice.selectionRows;
            materials.map((p) => {
                this.entityObj.deliveryProtocolItems.push({
                    deliveryProtocolItemId: 0,
                    materialId: p.materialId,
                    materialCode: p.materialCode,
                    materialName: p.materialName,
                    materialSpecs: p.materialSpecs,
                    materialTypeId: p.materialTypeId,
                    materialTypeName: p.materialTypeName,
                    materialSimpCode: p.materialSimpCode,
                    unitCode:
                        p.materialItems.length > 0
                            ? p.materialItems.find((p) => p.isMinUnit)?.unitCode
                            : "",
                    unitName:
                        p.materialItems.length > 0
                            ? p.materialItems.find((p) => p.isMinUnit)?.unitName
                            : "",
                    price: 0.0,
                    remarks: "",
                    materialItemId:
                        p.materialItems.length > 0
                            ? p.materialItems.find((p) => p.isMinUnit)
                                  ?.materialItemId
                            : null,
                    materialItems: p.materialItems,
                    ticketType: 0,
                    generalRate: p.generalRate,
                    incrementRate: p.incrementRate,
                    isDisposable: false,
                    protocolItemRelations: [],
                });
            });
            this.$refs.scMaterialChoice.selectionRows = [];
            this.$refs.scMaterialChoice.opBindData();
            this.materialState = false;
            this.queryList = {};
            this.handleSearch();
        },
        //有效期调整(主表的有效期调整，所有明细表的有效期跟着调整)
        changeProtocolDate(val) {
            // this.entityObj.deliveryProtocolItems.map((p) => {
            //     if (p.deliveryProtocolItemPrices.length >= 1) {
            //         p.deliveryProtocolItemPrices[
            //             p.deliveryProtocolItemPrices.length - 1
            //         ].validityDates[0] = val[0];
            //         p.deliveryProtocolItemPrices[0].validityDates[1] = val[1];
            //     }
            // });
        },
        //调价
        opSetRowPrice(row) {
            // if (
            //     !this.entityObj.protocolDate ||
            //     this.entityObj.protocolDate.length < 2
            // ) {
            //     this.$message.error("请先设置有效期");
            //     return;
            // }

            // 获取当前时间
            const currentDate = new Date();
            // 获取 2 年后的时间
            const twoYearsLater = new Date();
            twoYearsLater.setFullYear(currentDate.getFullYear() + 2);

            if (!row.deliveryProtocolItemPrices||row.deliveryProtocolItemPrices.length == 0) {
                row.deliveryProtocolItemPrices = [
                    {
                        price: row.price,
                        validityDates: [currentDate, twoYearsLater],
                    },
                ];
            }

            this.dialogPrice = true;
            this.$nextTick(() => {
                this.$refs.priceDialog.setData({
                    ...row,
                    purchaseUnityId: this.entityObj.purchaseUnityId,
                    startDate: currentDate,
                    endDate: twoYearsLater,
                });
                this.$refs.priceDialog.open("Edit");
            });
        },
        //设置为正常物料
        setIsDisposable(row) {
            row.isDisposable = false;
        },
        //调价
        setPrice(data) {
            var obj = this.entityObj.deliveryProtocolItems.find(
                (p) => p.materialItemId == data.materialItemId
            );
            obj.deliveryProtocolItemPrices = data.deliveryProtocolItemPrices;
            obj.protocolItemRelations = data.protocolItemRelations;
            obj.notes=data.notes;
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        //要货类型变更
        async storeOrgTypeChange(){
            this.entityObj.store = {};
            this.entityObj.storeId = 0;
        },
        //获取要货门店
        async storeSelectProcess(rowData) {
            this.entityObj.store = rowData;
            this.entityObj.storeId = rowData.storeId;
        },
        //获取要货供应商
        async supplierSelectProcess(rowData) {
            this.entityObj.store = {storeId:rowData.supplierId,storeCode:rowData.supplierCode,storeName:rowData.supplierName};
            this.entityObj.storeId = rowData.supplierId;
        },
    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
        this.entityObj.purchaseUnityName = tool.data.get("USER_INFO").OrgName;
        this.entityObj.crName = tool.data.get("USER_INFO").Name;
        this.entityObj.crDate = this.formatDate(new Date());
        await this.initOptions();
    },
};
</script>

<style lang="scss" scoped>
/* 当表格行处于悬停状态时改变背景颜色 */
::v-deep .el-table .el-table__row:hover {
    background-color: #dae8f7;
}
::v-deep .el-table__body .el-table__row--striped.hover-row td {
    background-color: #dae8f7 !important;
}
//   斑马纹选中颜色
::v-deep .el-table__body .el-table__row--striped.selected-row-color td {
    background-color: #b8dcff !important;
}
::v-deep .el-table {
    --el-table-row-hover-bg-color: #dae8f7;
}

::v-deep .el-table tr:nth-child(2n) {
    background: #f2f2f2;
}
</style>
<style>
.el-table .selected-row-color {
    background-color: #b8dcff !important;
}
.el-table--enable-row-hover .el-table__body tr.selected-row-color:hover > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper .el-table__body tr.selected-row-color.hover-row > td {
    background-color: #b8dcff !important;
}
.el-table__fixed-body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > .el-table__row--striped {
    background-color: #b8dcff !important;
}
</style>
